package org.spbsu.apco.common.task.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spbsu.apco.common.Pair;
import org.spbsu.apco.common.properties.ApplicationPropertiesManager;
import org.spbsu.apco.common.properties.PropertyKey;
import org.spbsu.apco.common.task.core.BaseTask;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

/**
 * User: solozobov
 * Date: 25.11.12
 */

public class CommandLineTask extends BaseTask<String, Pair<Integer, String>> {
    private static final Logger LOG = LoggerFactory.getLogger(CommandLineTask.class);
    private static final List<String> commandLineExecutorArgs = Arrays.asList(ApplicationPropertiesManager.getProperty(PropertyKey.COMMAND_LINE_EXECUTOR, "bash -c").split(" "));

    @Override
    public Pair<Integer, String> execute(final List<String> inputData) throws Exception {
        try {
            ArrayList<String> cmdArgs = new ArrayList<String>(commandLineExecutorArgs);
            cmdArgs.add(inputData.get(0));
            final Process process = new ProcessBuilder().directory(new File(ApplicationPropertiesManager.getProperty(PropertyKey.COMMAND_LINE_EXECUTION_DIR, "/var/tmp")))
                                                        .command(cmdArgs)
                                                        .start();

            final StringBuilder result = new StringBuilder();
            final Scanner output = new Scanner(process.getInputStream());
            while (output.hasNextLine()) {
                result.append(output.nextLine()).append(System.getProperty("line.separator"));
            }
            process.waitFor();
            final int exitCode = process.exitValue();

            return Pair.of(exitCode, result.toString());
        } catch(Exception e) {
            LOG.error("Can't execute command " + inputData.get(0), e);
            return Pair.of(-1, "Can't execute command + inputData.get(0) " + Arrays.toString(e.getStackTrace()));
        }
    }
}
